package com.android.djlmapp.http;

import android.text.TextUtils;
import android.util.Log;

import com.android.djlmapp.tools.global.GlobalContants;
import com.android.djlmapp.tools.other.TextUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created by yucheng on 2018/3/27.
 */

public class ComPareUtils {
    private Map<String, String> mParams;

    private ComPareUtils(ComPareBuilder builder) {
        mParams = builder.mParams;
    }

    public static class ComPareBuilder {
        private TreeMap<String, String> mParams = new TreeMap<String, String>(
                new Comparator<String>() {
                    @Override
                    public int compare(String obj1, String obj2) {
                        // 升序排序
                        return obj1.compareTo(obj2);
                    }
                });

        public ComPareBuilder put(String key, String value) {
            this.mParams.put(key, value);
            return this;
        }

        public ComPareBuilder putMap(Map<String, String> map) {
            Set<String> keySet = map.keySet();
            for (String key : keySet) {
                if (!TextUtils.isEmpty(key)) {
                    put(key, map.get(key));
                }
            }
            return this;
        }

        public ComPareUtils create() {
            Set<String> keySet = mParams.keySet();
            Iterator<String> iter = keySet.iterator();
            StringBuilder stringBuilder = new StringBuilder();
            while (iter.hasNext()) {
                String key = iter.next();
                stringBuilder.append(mParams.get(key));
            }
            return new ComPareUtils(this);
        }
    }

    public String getSignString() {
        if (mParams == null) {
            throw new NullPointerException("未传入加密参数");
        }
        Collection<String> keySet = mParams.keySet();
        List<String> list = new ArrayList<String>(keySet);
        Collections.sort(list);
        String paramStr = GlobalContants.PUBLIC_KEY;

        for (int i = 0; i < list.size(); i++) {
            // 拼接键值对
            paramStr += (list.get(i) + mParams.get(list.get(i)));
        }
        Log.e("签名参数", "------paramStr------" + paramStr);
        String encode = TextUtil.encode(paramStr);
        return encode;
    }


}
